import sys
from PyQt5 import QtWidgets, uic

from can_process import CANController


class MyWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        # 加载 UI 文件
        uic.loadUi('../ui/window.ui', self)
        self.can_controller = CANController(self)

        # 预留接口
        self.setup_menu()
        self.setup_connections()

    def setup_connections(self):
        self.pushButtonOpen.clicked.connect(self.open_can)  # 连接打开按钮
        self.pushButtonClose.clicked.connect(self.close_can)  # 连接关闭按钮
        self.pushButtonSend.clicked.connect(self.send_messages)  # 连接发送按钮
        self.pushButtonClearCount.clicked.connect(self.clear_count)  # 连接清空计数按钮

    def open_can(self):
        self.can_controller.start()  # 启动 CAN 控制器

    def close_can(self):
        self.can_controller.stop()  # 停止 CAN 控制器

    def send_messages(self):
        self.can_controller.send_messages()  # 发送 CAN 消息



    def update_table(self, timestamp, can_id, dlc, eff, rtr, data):
        # print("更新表格");
        row_position = self.tableWidgetData.rowCount()
        self.tableWidgetData.insertRow(row_position)
        self.tableWidgetData.setItem(row_position, 1, QtWidgets.QTableWidgetItem(str(timestamp)))
        self.tableWidgetData.setItem(row_position, 2, QtWidgets.QTableWidgetItem('接收'))
        self.tableWidgetData.setItem(row_position, 3, QtWidgets.QTableWidgetItem(str(can_id)))
        self.tableWidgetData.setItem(row_position, 4, QtWidgets.QTableWidgetItem(str(dlc)))
        # self.tableWidgetData.setItem(row_position, 3, QtWidgets.QTableWidgetItem(str(eff)))
        # self.tableWidgetData.setItem(row_position, 4, QtWidgets.QTableWidgetItem(str(rtr)))
        self.tableWidgetData.setItem(row_position, 5, QtWidgets.QTableWidgetItem(data))
        # 滚动到最后一行
        self.tableWidgetData.scrollToBottom()

    def clear_count(self):
        # 清空计数的逻辑
        print("计数已清空")  # 这里可以添加实际的清空逻辑


    def setup_menu(self):
        # 在这里设置菜单
        pass


    def update_ui(self):
        # 在这里更新 UI
        pass